package com.zff.rental.service.dict;

import com.zff.rental.entity.dict.KeyValueDict;
import com.zff.rental.repository.dict.KeyValueDictRepository;
import com.zff.rental.vo.dict.KeyValueDictIdParams;
import com.zff.rental.vo.dict.KeyValueDictParams;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author HCY
 */
@Service
public class KeyValueDictServer {
    @Resource
    private KeyValueDictRepository keyValueDictRepository;

    public KeyValueDict add(KeyValueDictParams params) {
        KeyValueDict po = params.toEntity();
        return keyValueDictRepository.save(po);
    }

    public Boolean remove(KeyValueDictIdParams params) {
        keyValueDictRepository.deleteById(params.toEntityId());
        return true;
    }

    public List<KeyValueDict> listByType(Integer type) {
        List<KeyValueDict> result = keyValueDictRepository.findAllByType(type);
        result.sort(Comparator.comparingInt(e -> e.getSerialNumber() == null ? Integer.MAX_VALUE : e.getSerialNumber()));
        return result;
    }

    public Map<Integer, List<KeyValueDict>> listByTypes(List<Integer> types) {
        Map<Integer, List<KeyValueDict>> result = keyValueDictRepository.findAllByTypeIn(types).stream().collect(Collectors.groupingBy(KeyValueDict::getType));
        result.forEach((type, list) -> list.sort(Comparator.comparingInt(e -> e.getSerialNumber() == null ? Integer.MAX_VALUE : e.getSerialNumber())));
        return result;
    }

    public List<KeyValueDict> batchModify(List<KeyValueDictParams> params) {
        List<KeyValueDict> list = params.stream().map(KeyValueDictParams::toEntity).toList();
        return keyValueDictRepository.saveAll(list);
    }
}
